package com.jinzheng.qhnetty.util.testjinzhengclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * @CLassName NettyClient
 * @Description TODO
 * @Author xxmfypp
 * @Date 2023/1/14 11:10
 * @Version 1.0
 **/
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Channel channel = null;
        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            /**
             * 设置相关参数
             * 设置线程组
             * 设置客户端通道实现类（反射）
             */
            bootstrap.group(group)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            System.out.println("Client OK ...");
            //启动客户端 连接服务端
            ChannelFuture cf = bootstrap.connect("127.0.0.1",7788).sync();
            channel =  cf.channel();
            for(int i=0;i<10;i++){
                ByteBuf escapeData = Unpooled.copiedBuffer("Hello Server "+i+"\n", CharsetUtil.UTF_8);
                channel.writeAndFlush(escapeData);
            }
            //关闭通道增加监听
            cf.channel().closeFuture().addListener(fu -> {
                System.out.println("连接关闭");
            });
        }finally {
            group.shutdownGracefully();
        }
    }

    static  class NettyClientHandler  extends ChannelInboundHandlerAdapter {

        /**
         * 当通道就绪就会触发
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
//            System.out.println("Client :" + ctx);
//            ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Server ", CharsetUtil.UTF_8));
        }

        /**
         * 当通道有读取事件时会触发
         * @param ctx
         * @param msg
         * @throws Exception
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("Server SendBack Message:" + buf.toString(CharsetUtil.UTF_8));
            System.out.println("Server Ip Address :" + ctx.channel().remoteAddress());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }


}
